<template>
  <div>
    <canvas id="myCanvas1" ref="myCanvas1" height="750" width="375" style="width: 375px;height: 750px;border: 1px solid; border-radius: 8px"></canvas>
    <img src="../../../assets/logo.png" ref="img" alt="">
  </div>
</template>

<script>
  export default {
    name: "canvasDemo",
    methods: {
      fn(title, context, font) {
        context.font = font.style;
        context.fillStyle = font.color;
        let l = title.length;
        let t = context.measureText(title)
        if (t.width >= 335) {
          let s = t.width / l; // 获取每个字的宽度
          let len = Math.ceil(335/s) ;// 获取一行能容纳的宽度
          let n = title.substring(0, len); //
          let n2 = title.substring(len, len*2-2)

          context.fillText(n, 20, font.y);
          context.fillText(n2+'...', 20, font.y+20);
        }
      }
    },
    mounted() {
      debugger
      const canvas = this.$refs.myCanvas1;
      const context = canvas.getContext('2d');
      context.height = 750;
      context.width = 375;
      // context.rect(0, 0, 100, 100);
      // context.strokeRect(0, 0, 100, 50);
      // context.fillRect(0, 0, 50, 50);
      context.rect(20, 20, 40, 40);
      context.strokeRect(20, 20, 40, 40);
      context.drawImage(this.$refs.img, 20, 20, 40, 40)


      context.textBaseline = 'middle';
      context.font = '16px bold sans-serif';
      context.fillText('nihao', 70, 30); // 文字定位是左下角而非左上角，并且字母占用的高度和汉字也是有区别的，https://blog.csdn.net/haoyanyu_/article/details/108509098
      context.font = '12px sans-serif';
      context.fillStyle = '#c6c6c6';
      context.textBaseline = 'bottom';
      context.fillText('2022-03-31', 70, 60)

      context.drawImage(this.$refs.img, 20, 80, 335, 335);
      context.strokeRect(20, 80, 335, 335);

      let title = '抱团的方式解放螺丝钉解放了睡觉了房间但是势力扩大飞机离开是抱团的方式解放螺丝钉解放了睡觉了房间但是势力扩大飞机离开是';
      this.fn(title, context, {
        style: '16px bold sans-serif',
        color: '#000000',
        y: 445,
      })
      let title2 =  '抱团的方式解放螺丝钉解放了睡觉了房间但是势力扩大飞机离开是抱团的方式解放螺丝钉解放了睡觉了房间但是势力扩大飞机离开是';
      this.fn(title2, context, {
        style: '12px sans-serif',
        color: '#c6c6c6',
        y: 485,
      })


      // context.fillText(,)
    }
  }
</script>

<style scoped>

</style>
